#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const net = require('net')
const { spawn, execSync } = require('child_process');
const util = require('util');
const { exit } = require('process');

const download = (nwjs) => {
    return new Promise((resolve, reject) => {

        try {
            fs.mkdirSync(path.resolve(__dirname, "../cache"));
        } catch (error) {

        }

        let url = nwjs.url.replace('${version}', nwjs.version).replace('${version}', nwjs.version)


        let localPath = path.resolve(__dirname, "../cache", url.split("?")[0].split("/").slice(-1)[0]);

        if (fs.existsSync(localPath)) {
            console.info(`Cache available ${path.basename(localPath)}`);
            resolve(localPath);
            return;
        }
        console.info(`Downloading ${url}`);

        const wgetCMD = `wget -c ${url} -O ${localPath}.tmp`
        console.log(`执行 --- ${wgetCMD}`)
        const ls = spawn('wget', ['-c', url, '-O', `${localPath}.tmp`], { stdio: 'inherit' });

        // ls.stdout.on('data', (data) => {
        //     console.log(`stdout: ${data}`);
        // });

        // ls.stderr.on('data', (data) => {
        //     console.log(data.length)
        //     process.stderr.write(data);
        // });

        ls.on('close', (code) => {
            console.log(`child process exited with code ${code}`);
            fs.rename(`${localPath}.tmp`, localPath, err => {
                if (err) reject(err)
                else resolve(localPath)
            })
        });

    })
}
const extract = function (localPath) {
    return new Promise((resolve, reject) => {

        console.info(`Extracting ${localPath}`);

        let extractPath = path.resolve(__dirname, `../tmp/${path.basename(localPath)}`);

        execSync(`rm -rf ${extractPath}`)

        fs.mkdirSync(extractPath);

        console.log(`执行 tar -xf ${localPath} -C ${extractPath}`)
        // v参数可输出过程
        const tarP = spawn("tar", ["-xf", localPath, "-C", extractPath], { stdio: 'inherit' });
        tarP.on('error', (err) => {
            reject(err)
        })
        tarP.on('close', (code) => {

            console.log(`child process close all stdio with code ${code}`);

            resolve(extractPath);
        })
    })
}

const upgrade = function (extractPath) {

    return new Promise((resolve, reject) => {

        console.info(`Upgrading ${path.basename(extractPath)}`);

        execSync(`rm -rf ${path.resolve(__dirname, "../nwjs")}`);

        fs.renameSync(path.resolve(extractPath, fs.readdirSync(extractPath)[0]),
            path.resolve(__dirname, "../nwjs"))

        execSync(`rm -rf ${extractPath}`);

        if (fs.existsSync(path.resolve(__dirname, "../node/bin/node"))) {
            execSync(`cd ${path.resolve(__dirname, "../nwjs")} && ln -sr ../node/bin/node node`)
            execSync(`cd ${path.resolve(__dirname, "../nwjs")} && ln -s node node.exe`)
        }
        if (fs.existsSync(path.resolve(__dirname, "../package.nw"))) {
            execSync(`cd ${path.resolve(__dirname, "../nwjs")} && ln -sr ../package.nw package.nw`)
        }

        resolve();

    })
}
const init = async () => {
    try {
        const args = process.argv.slice(2);
        const nwjs = require("../conf/nwjs.json");
        if(args[0])nwjs.version = args[0]

        const localPath = await download(nwjs)
        const extractPath = await extract(localPath)
        const result = await upgrade(extractPath)

        console.info(`Succeeded upgrading nwjs to version ${nwjs.version}`);
    } catch (err) {

        if (err) {
            console.error('error--->', err);
        }
        exit(-1)
    }
}
init()